import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Home, ShoppingCart, Globe, Package, Check } from 'lucide-react';
import Button from '../../components/Button';
import { useLocalizedLink } from '../../hooks/useLocalizedLink';
import { useLanguage } from '../../contexts/LanguageContext';
import { useCart } from '../../contexts/CartContext';
import * as flags from 'country-flag-icons/react/3x2';

// 模拟国家库存数据
const countryInventory = [
  { code: 'US', name: 'United States', nameCN: '美国', stock: 1250 },
  { code: 'GB', name: 'United Kingdom', nameCN: '英国', stock: 850 },
  { code: 'DE', name: 'Germany', nameCN: '德国', stock: 920 },
  { code: 'FR', name: 'France', nameCN: '法国', stock: 780 },
  { code: 'JP', name: 'Japan', nameCN: '日本', stock: 650 },
  { code: 'CA', name: 'Canada', nameCN: '加拿大', stock: 540 },
  { code: 'AU', name: 'Australia', nameCN: '澳大利亚', stock: 480 },
  { code: 'SG', name: 'Singapore', nameCN: '新加坡', stock: 320 },
  { code: 'NL', name: 'Netherlands', nameCN: '荷兰', stock: 410 },
  { code: 'KR', name: 'South Korea', nameCN: '韩国', stock: 380 },
];

// 定价逻辑
const basePrices = {
  day: 0.03,
  week: 0.15,
  month: 0.45,
  year: 4.50,
};

// 批量折扣阶梯
const getDiscountRate = (quantity: number): number => {
  if (quantity >= 50) return 0.80;  // 20% off
  if (quantity >= 10) return 0.90;  // 10% off
  if (quantity >= 5) return 0.95;   // 5% off
  return 1.0;  // No discount
};

const PurchaseStaticResidential = () => {
  const { getLink } = useLocalizedLink();
  const { language } = useLanguage();
  const { addItem } = useCart();
  const navigate = useNavigate();
  
  // Minimum quantities to meet Stripe's $0.50 minimum payment
  const minimumQuantities = {
    day: 17,    // $0.03 × 17 = $0.51
    week: 4,    // $0.15 × 4 = $0.60
    month: 2,   // $0.45 × 2 = $0.90
    year: 1,    // $4.50 × 1 = $4.50
  };
  
  const [billingPeriod, setBillingPeriod] = useState<'day' | 'week' | 'month' | 'year'>('month');
  const [quantity, setQuantity] = useState<number>(minimumQuantities.month);
  const [selectedCountry, setSelectedCountry] = useState<string>('US');

  const selectedCountryData = useMemo(
    () => countryInventory.find(c => c.code === selectedCountry) || countryInventory[0],
    [selectedCountry]
  );

  // 计算总价
  const totalPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * quantity * discountRate).toFixed(2);
  }, [billingPeriod, quantity]);

  // 计算单价
  const unitPrice = useMemo(() => {
    const basePrice = basePrices[billingPeriod];
    const discountRate = getDiscountRate(quantity);
    return (basePrice * discountRate).toFixed(3);
  }, [billingPeriod, quantity]);

  const discountPercentage = useMemo(() => {
    const rate = getDiscountRate(quantity);
    return rate === 1.0 ? 0 : Math.round((1 - rate) * 100);
  }, [quantity]);

  const handleAddToCart = () => {
    const discountValue = discountPercentage / 100;
    addItem({
      productType: 'static-residential',
      quantity,
      period: billingPeriod,
      country: selectedCountry,
      countryName: language === 'zh-CN' ? selectedCountryData.nameCN : selectedCountryData.name,
      unitPrice: parseFloat(unitPrice),
      totalPrice: parseFloat(totalPrice),
      ...(discountValue > 0 && { discount: discountValue }),
    });
    navigate(getLink('/cart'));
  };

  const periodLabels = {
    day: language === 'zh-CN' ? '天' : 'Day',
    week: language === 'zh-CN' ? '周' : 'Week',
    month: language === 'zh-CN' ? '月' : 'Month',
    year: language === 'zh-CN' ? '年' : 'Year',
  };

  return (
    <div className="w-full">
      {/* Header */}
      <section className="bg-[#0f1c3f] dark:bg-gray-800 text-white py-16 transition-colors duration-300">
        <div className="container mx-auto px-4 text-center">
          <div className="inline-flex items-center justify-center p-2 bg-[#00d4ff]/10 rounded-full mb-4">
            <ShoppingCart className="text-[#00d4ff]" size={32} />
          </div>
          <h1 className="text-3xl md:text-4xl font-bold mb-4">
            {language === 'zh-CN' ? '静态住宅 IPv6 选购' : 'Purchase Static Residential IPv6'}
          </h1>
          <p className="text-xl text-gray-300 dark:text-gray-200 max-w-2xl mx-auto">
            {language === 'zh-CN' 
              ? '自定义您的静态住宅 IPv6 代理套餐，选择数量、周期和国家' 
              : 'Customize your Static Residential IPv6 proxy plan - choose quantity, period, and country'}
          </p>
        </div>
      </section>

      {/* Purchase Configuration */}
      <section className="bg-white dark:bg-gray-900 py-16 transition-colors duration-300">
        <div className="container mx-auto px-4 max-w-6xl">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Configuration Panel */}
            <div className="lg:col-span-2 space-y-6">
              {/* Billing Period Selection */}
              <div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
                <div className="flex items-center mb-4">
                  <Package className="text-[#00d4ff] mr-2" size={24} />
                  <h3 className="text-xl font-bold text-[#0f1c3f] dark:text-white">
                    {language === 'zh-CN' ? '选择计费周期' : 'Select Billing Period'}
                  </h3>
                </div>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  {(Object.keys(periodLabels) as Array<keyof typeof periodLabels>).map((period) => (
                    <button
                      key={period}
                      onClick={() => {
                        setBillingPeriod(period);
                        // Reset quantity to minimum when changing billing period
                        setQuantity(minimumQuantities[period]);
                      }}
                      className={`p-4 rounded-lg border-2 transition-all duration-300 ${
                        billingPeriod === period
                          ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#0f1c3f] dark:text-white font-bold'
                          : 'border-gray-300 dark:border-gray-600 hover:border-[#00d4ff]/50 text-gray-700 dark:text-gray-200'
                      }`}
                    >
                      <div className="text-lg font-semibold">{periodLabels[period]}</div>
                      <div className="text-sm text-gray-600 dark:text-gray-400">
                        ${basePrices[period].toFixed(2)}/{language === 'zh-CN' ? 'IP' : 'IP'}
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Quantity Selection */}
              <div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center">
                    <Home className="text-[#00d4ff] mr-2" size={24} />
                    <h3 className="text-xl font-bold text-[#0f1c3f] dark:text-white">
                      {language === 'zh-CN' ? '选择 IP 数量' : 'Select IP Quantity'}
                    </h3>
                  </div>
                  {discountPercentage > 0 && (
                    <span className="bg-green-500 text-white text-xs font-bold px-3 py-1 rounded-full">
                      {language === 'zh-CN' ? `立省 ${discountPercentage}%` : `${discountPercentage}% OFF`}
                    </span>
                  )}
                </div>
                
                <div className="space-y-4">
                  <div className="flex items-center gap-4">
                    <input
                      type="range"
                      min={minimumQuantities[billingPeriod]}
                      max="100"
                      value={quantity}
                      onChange={(e) => setQuantity(parseInt(e.target.value))}
                      className="flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-[#00d4ff]"
                    />
                    <input
                      type="number"
                      min={minimumQuantities[billingPeriod]}
                      max={selectedCountryData.stock}
                      value={quantity}
                      onChange={(e) => setQuantity(Math.max(minimumQuantities[billingPeriod], Math.min(selectedCountryData.stock, parseInt(e.target.value) || minimumQuantities[billingPeriod])))}
                      className="w-20 px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-center font-bold text-[#0f1c3f] dark:text-white bg-white dark:bg-gray-700"
                    />
                  </div>
                  
                  {/* Quick Select Buttons */}
                  <div className="flex flex-wrap gap-2">
                    {[1, 5, 10, 20, 50].map((num) => (
                      <button
                        key={num}
                        onClick={() => setQuantity(Math.min(num, selectedCountryData.stock))}
                        className={`px-4 py-2 rounded-lg border transition-all duration-300 ${
                          quantity === num
                            ? 'border-[#00d4ff] bg-[#00d4ff]/10 text-[#0f1c3f] dark:text-white font-bold'
                            : 'border-gray-300 dark:border-gray-600 hover:border-[#00d4ff]/50 text-gray-700 dark:text-gray-200'
                        }`}
                      >
                        {num} {language === 'zh-CN' ? '个' : 'IPs'}
                      </button>
                    ))}
                  </div>

                  {/* Discount Tiers Info */}
                  <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                    <p className="text-sm font-semibold text-blue-900 dark:text-blue-200 mb-2">
                      {language === 'zh-CN' ? '批量优惠' : 'Volume Discounts'}:
                    </p>
                    <ul className="text-xs text-blue-800 dark:text-blue-300 space-y-1">
                      <li className="flex items-center">
                        <Check size={14} className="mr-2" />
                        {language === 'zh-CN' ? '5-9 个 IP: 5% 折扣' : '5-9 IPs: 5% off'}
                      </li>
                      <li className="flex items-center">
                        <Check size={14} className="mr-2" />
                        {language === 'zh-CN' ? '10-49 个 IP: 10% 折扣' : '10-49 IPs: 10% off'}
                      </li>
                      <li className="flex items-center">
                        <Check size={14} className="mr-2" />
                        {language === 'zh-CN' ? '50+ 个 IP: 20% 折扣' : '50+ IPs: 20% off'}
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              {/* Country Selection */}
              <div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
                <div className="flex items-center mb-4">
                  <Globe className="text-[#00d4ff] mr-2" size={24} />
                  <h3 className="text-xl font-bold text-[#0f1c3f] dark:text-white">
                    {language === 'zh-CN' ? '选择国家/地区' : 'Select Country/Region'}
                  </h3>
                </div>
                
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
                  {countryInventory.map((country) => {
                    const FlagComponent = flags[country.code as keyof typeof flags];
                    return (
                      <button
                        key={country.code}
                        onClick={() => {
                          setSelectedCountry(country.code);
                          if (quantity > country.stock) {
                            setQuantity(country.stock);
                          }
                        }}
                        disabled={country.stock === 0}
                        className={`p-3 rounded-lg border-2 transition-all duration-300 ${
                          selectedCountry === country.code
                            ? 'border-[#00d4ff] bg-[#00d4ff]/10'
                            : 'border-gray-300 dark:border-gray-600 hover:border-[#00d4ff]/50'
                        } ${country.stock === 0 ? 'opacity-50 cursor-not-allowed' : ''}`}
                      >
                        <div className="w-full h-8 mb-2 flex items-center justify-center">
                          {FlagComponent && <FlagComponent className="w-10 h-7 rounded shadow-sm" />}
                        </div>
                        <div className="text-xs font-semibold text-[#0f1c3f] dark:text-white">
                          {language === 'zh-CN' ? country.nameCN : country.name}
                        </div>
                        <div className={`text-xs mt-1 ${
                          country.stock > 100 
                            ? 'text-green-600 dark:text-green-400' 
                            : country.stock > 20
                            ? 'text-yellow-600 dark:text-yellow-400'
                            : 'text-red-600 dark:text-red-400'
                        }`}>
                          {language === 'zh-CN' ? '库存' : 'Stock'}: {country.stock}
                        </div>
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Order Summary */}
            <div className="lg:col-span-1">
              <div className="bg-white dark:bg-gradient-to-br dark:from-gray-800 dark:to-gray-900 rounded-xl p-6 sticky top-20 border-2 border-gray-200 dark:border-[#00d4ff]/30 shadow-lg">
                <h3 className="text-2xl font-bold mb-6 flex items-center text-[#0f1c3f] dark:text-white">
                  <ShoppingCart className="mr-2" size={24} />
                  {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
                </h3>

                <div className="space-y-4 mb-6">
                  <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                    <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '产品' : 'Product'}:</span>
                    <span className="font-semibold text-gray-900 dark:text-white">{language === 'zh-CN' ? '静态住宅 IPv6' : 'Static Residential IPv6'}</span>
                  </div>

                  <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                    <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '数量' : 'Quantity'}:</span>
                    <span className="font-semibold text-gray-900 dark:text-white">{quantity} IPs</span>
                  </div>

                  <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                    <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '计费周期' : 'Billing Period'}:</span>
                    <span className="font-semibold text-gray-900 dark:text-white">{periodLabels[billingPeriod]}</span>
                  </div>

                  <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                    <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '国家' : 'Country'}:</span>
                    <span className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                      {(() => {
                        const FlagComponent = flags[selectedCountryData.code as keyof typeof flags];
                        return FlagComponent && <FlagComponent className="w-5 h-3.5 rounded shadow-sm inline-block" />;
                      })()}
                      {language === 'zh-CN' ? selectedCountryData.nameCN : selectedCountryData.name}
                    </span>
                  </div>

                  <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                    <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '单价' : 'Unit Price'}:</span>
                    <span className="font-semibold text-gray-900 dark:text-white">${unitPrice}/{language === 'zh-CN' ? 'IP' : 'IP'}</span>
                  </div>

                  {discountPercentage > 0 && (
                    <div className="flex justify-between items-center pb-3 border-b border-gray-200 dark:border-white/20">
                      <span className="text-gray-600 dark:text-gray-300">{language === 'zh-CN' ? '折扣' : 'Discount'}:</span>
                      <span className="font-semibold text-green-600 dark:text-green-400">-{discountPercentage}%</span>
                    </div>
                  )}
                </div>

                <div className="bg-gray-50 dark:bg-white/10 rounded-lg p-4 mb-6 border border-gray-200 dark:border-white/10">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-lg text-gray-700 dark:text-gray-300">{language === 'zh-CN' ? '总计' : 'Total'}:</span>
                    <span className="text-3xl font-bold text-[#00d4ff]">${totalPrice}</span>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 text-right">
                    {language === 'zh-CN' ? `按${periodLabels[billingPeriod]}计费` : `per ${periodLabels[billingPeriod]}`}
                  </p>
                </div>

                <Button variant="gradient" fullWidth size="lg" onClick={handleAddToCart}>
                  <span className="flex items-center justify-center gap-2">
                    <ShoppingCart size={20} />
                    {language === 'zh-CN' ? '加入购物车' : 'Add to Cart'}
                  </span>
                </Button>

                <p className="text-xs text-gray-400 text-center mt-4">
                  {language === 'zh-CN' 
                    ? '购买后立即激活，支持多种支付方式' 
                    : 'Instant activation after purchase, multiple payment methods supported'}
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Features Section */}
      <section className="py-12 bg-gray-50 dark:bg-gray-800/50 transition-colors duration-300">
        <div className="container mx-auto px-4 max-w-6xl">
          <h2 className="text-2xl font-bold text-[#0f1c3f] dark:text-white mb-8 text-center">
            {language === 'zh-CN' ? '为什么选择静态住宅 IPv6？' : 'Why Choose Static Residential IPv6?'}
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div className="bg-white dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
              <div className="inline-flex items-center justify-center w-12 h-12 bg-[#00d4ff]/10 rounded-full mb-4">
                <Home className="text-[#00d4ff]" size={24} />
              </div>
              <h3 className="text-lg font-bold text-[#0f1c3f] dark:text-white mb-2">
                {language === 'zh-CN' ? '真实住宅 IP' : 'Real Residential IPs'}
              </h3>
              <p className="text-gray-600 dark:text-gray-300 text-sm">
                {language === 'zh-CN' 
                  ? '来自真实 ISP 的住宅 IP 地址，高匿名性和可信度' 
                  : 'Real residential IP addresses from ISPs with high anonymity and trust'}
              </p>
            </div>
            
            <div className="bg-white dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
              <div className="inline-flex items-center justify-center w-12 h-12 bg-[#00d4ff]/10 rounded-full mb-4">
                <Globe className="text-[#00d4ff]" size={24} />
              </div>
              <h3 className="text-lg font-bold text-[#0f1c3f] dark:text-white mb-2">
                {language === 'zh-CN' ? '全球覆盖' : 'Global Coverage'}
              </h3>
              <p className="text-gray-600 dark:text-gray-300 text-sm">
                {language === 'zh-CN' 
                  ? '覆盖全球主要国家和地区，满足不同业务需求' 
                  : 'Coverage across major countries and regions worldwide for diverse business needs'}
              </p>
            </div>
            
            <div className="bg-white dark:bg-gray-800 rounded-xl p-6 border border-gray-200 dark:border-gray-700">
              <div className="inline-flex items-center justify-center w-12 h-12 bg-[#00d4ff]/10 rounded-full mb-4">
                <Package className="text-[#00d4ff]" size={24} />
              </div>
              <h3 className="text-lg font-bold text-[#0f1c3f] dark:text-white mb-2">
                {language === 'zh-CN' ? '灵活计费' : 'Flexible Billing'}
              </h3>
              <p className="text-gray-600 dark:text-gray-300 text-sm">
                {language === 'zh-CN' 
                  ? '支持按天/周/月/年计费，满足不同使用场景' 
                  : 'Support for daily, weekly, monthly, and yearly billing to fit different use cases'}
              </p>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default PurchaseStaticResidential;
